
import * as vscode from 'vscode';
import { disconnect } from "process";
import { Console } from "console";
export class ttpaleditor implements vscode.CustomTextEditorProvider
{
    exturi: vscode.Uri;
    constructor(uri: vscode.Uri)
    {
        this.exturi = uri;
    }
    resolveCustomTextEditor(document: TextDocument, webviewPanel: WebviewPanel, token: CancellationToken): void | Thenable<void>
    {

        //#region 呈现webview
            let urimedia = vscode.Uri.joinPath(this.exturi, 'media');

            let option: vscode.WebviewOptions = {
                enableScripts: true,//是否允许webview中执行js，那必须的啊
                localResourceRoots: [urimedia]//如果要允许访问本地文件，这里需要配置路径
            };
            webviewPanel.webview.options = option;

            let urigif = webviewPanel.webview.asWebviewUri(vscode.Uri.joinPath(urimedia, 'giphy.gif'));
            let urijs = webviewPanel.webview.asWebviewUri(vscode.Uri.joinPath(urimedia, 'view.js'));
            webviewPanel.webview.html = GetInitHtmlWithRes(urigif, urijs);
        //#endregion


        //#region 处理文档变化事件
        var evt = vscode.workspace.onDidChangeTextDocument((e) =>
        {
            if (e.document.uri.toString() === document.uri.toString())//设置一个文件变化回调
            {
                webviewPanel.webview.postMessage({ "type": "update", "data": document.getText() });
            }
        });
        //当文档销毁时停止订阅
        webviewPanel.onDidDispose((e) =>
        {
            evt.dispose();
        });
        //#endregion
    

        //#region 处理webview事件
        //收到来自编辑器的事件
        webviewPanel.webview.onDidReceiveMessage(e =>
        {
            //这里简单处理，无论编辑器发来啥，把他存起来
            var txtnew = "";
            if (typeof (e) == "string")
            {
                txtnew = e;
            }
            else
            {
                txtnew = "recv " + JSON.stringify(e);
            }

            if (document.getText() == txtnew)//文件没变，别发了
            {
                console.log("file has not change.");
                return;
            }

            const edit = new vscode.WorkspaceEdit();
            //创建一个编辑操作
            edit.replace(
                document.uri,
                new vscode.Range(0, 0, document.lineCount, 0),
                txtnew
            )
            return vscode.workspace.applyEdit(edit);


        });
        //#endregion

        //把文件内容发给自定义webview
        webviewPanel.webview.postMessage({ "type": "update", "data": document.getText() });
    }



}

export class tthex implements  vscode.CustomEditorProvider
{

}
function GetInitHtmlWithRes(urigif: vscode.Uri, urijs: vscode.Uri)
{
    let inithtml =
        `
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Cat Coding</title>
	<script src="${urijs}"></script>
</head>
<body>
	<img src="${urigif}" width="300" />
</body>
</html>
`;
    return inithtml;
}
